package org.example.codetrail.controller;

import org.example.codetrail.pojo.Gitee.GiteeRepo;
import org.example.codetrail.pojo.Gitee.GiteeRepoContent;
import org.example.codetrail.pojo.Repository;
import org.example.codetrail.pojo.Result;
import org.example.codetrail.pojo.User;
import org.example.codetrail.service.RepoService;
import org.example.codetrail.utils.GiteeRepoFetcher;
import org.example.codetrail.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/repo")
public class RepoController {
    @Autowired
    private RepoService repoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/add")
    public Result add(String html_url,String full_name) throws IOException {
        Repository repository = repoService.findByHtmlUrl(html_url);
        if (repository == null) {
            repoService.register(html_url,full_name);
            return Result.success();
        } else {
            return Result.error("仓库已在库中");
        }
    }

    @GetMapping("/getLocalRepo")
    public Result<List<Repository>> getLocalRepo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        return Result.success(repoService.getLocalRepo(userId));
    }


    @PostMapping("/contents/get")
    public Result<List<GiteeRepoContent>> getInfo(Integer repositoryId, String path) throws IOException {
        Repository repo = repoService.getLocalRepoInfo(repositoryId);
        System.out.println(repo);
        if (path==null){
            System.out.println(1);
            GiteeRepoContent[] reposContentsArray = GiteeRepoFetcher.getFileContent(repo.getSourceAccount(),repo.getRepositoryName(),"/",repo.getAccessToken());
            // 将数组转换为 List
            List<GiteeRepoContent> reposContentsList = Arrays.asList(reposContentsArray);
            // 返回转换后的 List
            return Result.success(reposContentsList);
        }
        else {
            System.out.println(2);
            GiteeRepoContent[] reposContentsArray = GiteeRepoFetcher.getFileContent(repo.getSourceAccount(),repo.getRepositoryName(),path,repo.getAccessToken());
            // 将数组转换为 List
            List<GiteeRepoContent> reposContentsList = Arrays.asList(reposContentsArray);
            // 返回转换后的 List
            return Result.success(reposContentsList);

        }
    }

}
